package com.lgj.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lgj.mall.common.utils.R;
import com.lgj.mall.ware.feign.ProductFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lgj.mall.common.utils.PageUtils;
import com.lgj.mall.common.utils.Query;

import com.lgj.mall.ware.dao.WareSkuDao;
import com.lgj.mall.ware.entity.WareSkuEntity;
import com.lgj.mall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //如果没有库存记录,就新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        //查询这个商品在哪个仓库有库，就更新库存
        if(wareSkuEntities==null||wareSkuEntities.size() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //难点:远程获取sku(商品的名字)
          try{
              R info = productFeignService.info(skuId);
              Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
              if(info.getCode()==0){
                  wareSkuEntity.setSkuName((String) data.get("skuName"));
              }
          }catch (Exception e){
              log.error("远程调用失败");
          }
          //添加到仓库库存里
          wareSkuDao.insert(wareSkuEntity);
        }else{
            //更新库存(另外自己实现的)
            wareSkuDao.addStock(skuId, wareId,skuNum);
        }

    }
}